{extend name="base:base-add" /}
{block name="style"}
<link rel="stylesheet" type="text/css" href="__LIB__/markdown/lib/codemirror/codemirror.min.css">
<link rel="stylesheet" type="text/css" href="__LIB__/markdown/css/editormd.css">
<link rel="stylesheet" type="text/css" href="__LIB__/webuploader/0.1.5/webuploader.css">
{/block}
{block name="title"}
<title>添加文章</title>
{/block}
{block name="form"}
<form class="form form-horizontal" id="form-article-add" enctype="multipart/form-data">
    <div class="row clearfix">
        <label class="form-label col-xs-4 col-sm-1"><span class="c-red">*</span>所属分类：</label>
        <div class="form-controls col-xs-8 col-sm-1">
                <span class="select-box">
                    <select name="category_id" class="select">
                        {notempty name="to_level"}
                        <option value="0">|-根分类</option>
                        {volist name="to_level" id="vo"}
                        <option value="{$vo.id}" {if condition="$data.category_id == $vo.id " } selected="selected" {/if}>|-{$vo.delimiter}{$vo.name}</option>
                        {/volist}
                        {else /}
                        <option value="0">├根分类</option>
                        {/notempty}
                </select>
                </span>
        </div>
    </div>
    <div class="row clearfix">
        <label class="form-label col-xs-4 col-sm-1"><span class="c-red">*</span>文章标题：</label>
        <div class="form-controls col-xs-8 col-sm-4">
            <input type="text" class="input-text" value="{$data.title}" placeholder="" id="title" name="title">
        </div>
    </div>
    <div class="row clearfix">
        <label class="form-label col-xs-4 col-sm-1">副标题：</label>
        <div class="form-controls col-xs-8 col-sm-4">
            <input type="text" class="input-text" value="{$data.ftitle}" placeholder="" id="ftitle" name="ftitle">
        </div>
    </div>
    <div class="row clearfix">
        <label class="form-label col-xs-4 col-sm-1">缩略图：</label>

        <div class="formControls col-xs-8 col-sm-10">
            <div class="uploader-thum-container">
                <div id="fileList" class="uploader-list"></div>
                <div id="filePicker">选择文件</div>
                <button id="btn-star" type="button" class="btn btn-default btn-uploadstar radius ml-10">开始上传</button>
            </div>
            <div id="imageInput">
            </div>
            <div class="uploader-thum-container">
                <img src="{$data.thumbnail}" alt="" id="thumbnail" style="">
            </div>
        </div>
    </div>
    <div class="row clearfix">
        <label class="form-label col-xs-4 col-sm-1">关键词：</label>
        <div class="form-controls col-xs-8 col-sm-4">
            <input type="text" class="input-text" value="{$data.keywords}" placeholder="" id="keywords" name="keywords">
        </div>
    </div>
    <div class="row clearfix">
        <label class="form-label col-xs-4 col-sm-1">描述：</label>
        <div class="form-controls col-xs-8 col-sm-4">
            <textarea name="description" cols="" rows="" class="textarea" placeholder="说点什么...最少输入10个字符">{$data.description}</textarea>
            <p class="textarea-numberbar"><em class="textarea-length">0</em>/100</p>
        </div>
    </div>
    <div class="row clearfix">
        <label class="form-label col-xs-4 col-sm-1">状态：</label>
        <div class="form-controls col-xs-8 col-sm-4">
            <div class="radio-box">
                <input name="status" type="radio" id="1" value="1" {if condition="$data.status == 1" } checked {/if}>
                <label>正常</label>
            </div>
            <div class="radio-box">
                <input type="radio" id="2" name="status" value="2" {if condition="$data.status == 2" } checked {/if}>
                <label>禁用</label>
            </div>
        </div>
    </div>
    <div class="row clearfix">
        <label class="form-label col-xs-4 col-sm-1">推荐：</label>
        <div class="form-controls col-xs-8 col-sm-4">
            <div class="radio-box">
                <input name="mark" type="radio" id="yes" value="2" {if condition="$data.mark == 2" } checked {/if}>
                <label for="yes">推荐</label>
            </div>
            <div class="radio-box">
                <input name="mark" type="radio" id="no" value="1" {if condition="$data.mark == 1" } checked {/if}>
                <label for="no">不推</label>
            </div>
        </div>
    </div>
    <!--<div class="row clearfix">-->
    <!--<label for="thumbnail" class="form-label col-xs-4 col-sm-1">缩略图：</label>-->
    <!--<div class="form-controls col-xs-8 col-sm-4">-->
    <!--<span class="btn-upload">-->
    <!--<a href="javascript:void(0);" onclick="add('插入图片','/{$backendPrefix}/static/image/list.html')"-->
    <!--class="btn btn-primary radius btn-upload"><i class="Hui-iconfont">&#xe642;</i> 浏览文件</a>-->
    <!--</span>-->
    <!--<div style="width: 310px;margin: 10px 0;" class="add-img">-->
    <!--<img src="{$fileHost}{$data.thumbnail}" class="img-responsive center-block" />-->
    <!--<input type="hidden" id="thumbnail" name="thumbnail" value="{$data.thumbnail}">-->
    <!--</div>-->
    <!--</div>-->
    <!--</div>-->
    <div class="row clearfix">
        <label class="form-label col-xs-4 col-sm-1">文章内容：</label>
        <div class="form-controls col-xs-11 col-sm-11">
            <div id="markdown">
                <textarea name='markdown' style="display:none;" placeholder="数据库features字段，使用html代码，li标签 ">{$data.markdown}</textarea>
            </div>
        </div>
    </div>
    <div class="row clearfix">
        <label class="form-label col-xs-4 col-sm-1">参考文献：</label>
        <div class="form-controls col-xs-11 col-sm-11">
            <div id="refer">
                <textarea name='refer' style="display:none;"
                          placeholder="数据库features字段，使用html代码，li标签 ">{$data.refer}</textarea>
            </div>
        </div>
    </div>
    <input type="hidden" value="{$data.id}" name="id">
    <div class="row clearfix">
        <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-2">
            <button class="btn btn-secondary radius add" type="button"><i class="Hui-iconfont">&#xe632;</i>
                保存
            </button>
        </div>
    </div>
</form>
{/block}
{block name="script"}
<script type="text/javascript" src="__LIB__/markdown/editormd.js"></script>
<script type="text/javascript" src="__LIB__/webuploader/0.1.5/webuploader.js"></script>
<script>
    /*资讯-添加*/
    function add(title, url) {
        var index = layer.open({
            type: 2,
            title: title,
            content: url,
            area: ['800px', '200px']
        });
    }

    var Editor;
    var markdown;
    var refer;
    $(function () {
        markdown = Editor = editormd("markdown", {
            width: "100%",
            height: 960,
            path: "__LIB__/markdown/lib/",
            htmlDecode: "style,script",
            tex: true,
            emoji: true,
            taskList: true,
            flowChart: true,
            sequenceDiagram: true,
            saveHTMLToTextarea: true,
            imageUpload: true,
            imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL: "/{$backendPrefix}/aws/image/markdownUpload.html"
        });
        refer = Editor = editormd("refer", {
            width: "100%",
            height: 320,
            path: "__LIB__/markdown/lib/",
            htmlDecode: "style,script,iframe",
            tex: true,
            emoji: true,
            taskList: true,
            flowChart: true,
            sequenceDiagram: true,
            saveHTMLToTextarea: true,
        });
    });
</script>
<script type="text/javascript">
    // // 初始化Web Uploader
    // var uploader = WebUploader.create({
    //
    //     // 选完文件后，是否自动上传。
    //     auto: true,
    //
    //     // swf文件路径
    //     swf: '__LIB__/webuploader/0.1.5/Uploader.swf',
    //
    //     // 文件接收服务端。
    //     server: '/wavlink/aws/uploader.html',
    //
    //     // 选择文件的按钮。可选。
    //     // 内部根据当前运行是创建，可能是input元素，也可能是flash.
    //     pick: '#filePicker',
    //
    //     // 只允许选择图片文件。
    //     accept: {
    //         title: 'Images',
    //         extensions: 'gif,jpg,jpeg,bmp,png',
    //         mimeTypes: 'image/*'
    //     }
    // });
    // // 当有文件添加进来的时候
    // uploader.on( 'fileQueued', function( file ) {
    //     // var $li = $(
    //     //     '<div id="' + file.id + '" class="file-item thumbnail">' +
    //     //     '<img>' +
    //     //     '<div class="info">' + file.name + '</div>' +
    //     //     '</div>'
    //     //     )
    //     // // $list为容器jQuery实例
    //     // var $list = $("#fileList");
    //     // $list.append($li);
    //
    //     // 创建缩略图
    //     // 如果为非图片文件，可以不用调用此方法。
    //     // thumbnailWidth x thumbnailHeight 为 100 x 100
    //     uploader.makeThumb( file, function( error, src ) {
    //         if ( error ) {
    //             $('#thumbnail').replaceWith('<span>不能预览</span>');
    //             return;
    //         }
    //         $('#thumbnail').attr( 'style', 'display:none' );
    //         $('#thumbnail').attr( 'src', src );
    //     }, 450, 400 );
    // });
    // // 文件上传过程中创建进度条实时显示。
    // uploader.on( 'uploadProgress', function( file, percentage ) {
    //     var $li = $( '#'+file.id ),
    //         $percent = $li.find('.progress span');
    //
    //     // 避免重复创建
    //     if ( !$percent.length ) {
    //         $percent = $('<p class="progress"><span></span></p>')
    //             .appendTo( $li )
    //             .find('span');
    //     }
    //
    //     $percent.css( 'width', percentage * 100 + '%' );
    // });
    //
    // // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    // uploader.on( 'uploadSuccess', function(file,result) {
    //     $( '#'+file.id ).addClass('upload-state-done');
    //     $('#thumbnail').attr("src",result._raw);
    //     $('#thumbnail').attr( 'style', '' );
    //     console.log(result)
    // });
    //
    // // 文件上传失败，显示上传出错。
    // uploader.on( 'uploadError', function( file ) {
    //     var $li = $( '#'+file.id ),
    //         $error = $li.find('div.error');
    //
    //     // 避免重复创建
    //     if ( !$error.length ) {
    //         $error = $('<div class="error"></div>').appendTo( $li );
    //     }
    //
    //     $error.text('上传失败');
    // });
    //
    // // 完成上传完了，成功或者失败，先删除进度条。
    // uploader.on( 'uploadComplete', function( file ) {
    //     $( '#'+file.id ).find('.progress').remove();
    // });

    $(function () {
        var $list = $("#fileList");
        var $btn = $("#btn-star");
        var $imageInput = $("#imageInput");
        var state = "pending";
        uploader;
        var uploader = WebUploader.create({
            auto: false,
            swf: '__LIB__/webuploader/0.1.5/Uploader.swf',
            // 文件接收服务端。
            server: '/wavlink/aws/uploader.html',
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: {
                id: '#filePicker',
                label: '选择文件',
            },
            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            resize: false,
            method: 'POST',
            // fileNumLimit: 1,
            // 只允许选择图片文件。
            accept: {
                title: 'Files',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            }
        });
        uploader.on('fileQueued', function (file) {
            var $li = $(
                '<div id="' + file.id + '" class="item" style="display: inline-block; margin: 10px">' +
                '<div class="pic-box"><img></div>' +
                '<div class="info" style="width: 120px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden" title="' + file.name + '">' + file.name + '</div>' +
                '<p class="state">等待上传...</p>' +
                '</div>'
                ),
                $img = $li.find('img');
            $list.append($li);
            // 创建缩略图
            // 如果为非图片文件，可以不用调用此方法。
            // thumbnailWidth x thumbnailHeight 为 100 x 100
            uploader.makeThumb(file, function (error, src) {
                if (error) {
                    $img.replaceWith('<span>不能预览</span>');
                    return;
                }
                $img.attr('src', src);
            }, 100, 100);
        });
        // 文件上传过程中创建进度条实时显示。 percentage : 就是进度数字
        uploader.on('uploadProgress', function (file, percentage) {
            var $li = $('#' + file.id),
                $percent = $li.find('.progress-box .sr-only');
            // 避免重复创建
            if (!$percent.length) {
                $percent = $('<div class="progress-box"><span class="progress-bar radius"><span class="sr-only" style="width:0%"></span></span></div>').appendTo($li).find('.sr-only');
            }
            $li.find(".state").text("上传到亚马逊云");
            $percent.css('width', percentage * 100 + '%');
        });

        // 文件上传成功，给item添加成功class, 用样式标记上传成功。
        uploader.on('uploadSuccess', function (file, result) {
            $('#' + file.id).addClass('upload-state-success').find(".state").text("已上传至S3");
            var $input = $('<input type="hidden" name="aws_key" value="' + result._raw + '">');
            $imageInput.append($input);
            //console.log(result);
            $('#thumbnail').attr('src', '//files.wavlink.com/' + result._raw);
        });

        // 文件上传失败，显示上传出错。
        uploader.on('uploadError', function (file, reason) {
            $('#' + file.id).addClass('upload-state-error').find(".state").text(reason);
        });

        // 完成上传完了，成功或者失败，先删除进度条。
        uploader.on('uploadComplete', function (file) {
            $('#' + file.id).find('.progress-box').fadeOut();
        });
        uploader.on('all', function (type) {
            if (type === 'startUpload') {
                state = 'uploading';
            } else if (type === 'stopUpload') {
                state = 'paused';
            } else if (type === 'uploadFinished') {
                state = 'done';
            }
            if (state === 'uploading') {
                $btn.text('暂停上传');
            } else {
                $btn.text('开始上传');
            }
        });

        $btn.on('click', function () {
            if (state === 'uploading') {
                uploader.stop();
            } else {
                uploader.upload();
            }
        });
    });


    $(".add").click(function () {
        var postData = {};
        var data = $("form").serializeArray();
        $.each(data, function () {
            postData[this.name] = this.value
        });
        postData.thumbnail = $('#thumbnail').attr('src');
        //console.log(postData);
        //return false;
        $.ajax({
            url: "/{$backendPrefix}/article/edit/{$data.id}.html",
            type: "post",
            data: postData,
            "success": function (result) {
                var msgData = JSON.parse(result);
                if (msgData.status === true) {
                    layer.msg(msgData.message, {icon: 1, time: 1000}, function () {
                        window.parent.location.href = msgData.url
                    })
                } else {
                    layer.msg(msgData.message, {icon: 5, time: 2000})
                }
            }
        }, JSON);
    });

</script>
{/block}